//
//  TwERPAttachedFile.m
//  TwERP
//
//  Created by Xiangyang Li on 12-7-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TwERPAttachedFile.h"
#import "TwERPJsonAgent.h"

@implementation TwERPAttachedFile
@synthesize fileDescription = _fileDescription;
@synthesize url = _url;
@synthesize type = _type;
@synthesize fileDate = _fileDate;
@synthesize isPlaying = _isPlaying;
@synthesize uploadResult = _uploadResult;
@synthesize downloading = _downloading;
@synthesize recording = _recording;

+(NSString *)localDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}
-(void) setUrl:(id)url
{
    
    if ([url isKindOfClass:[NSURL class]])
        _url = url;
    else if  ([url isKindOfClass:[NSString class]])
    {
        _url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"file://localhost/%@", url]];
    }
     NSString *fileName = [_url lastPathComponent];
    
    NSString *directory =  [TwERPAttachedFile localDirectory];
    
    NSString *imgFilePath =   [directory stringByAppendingFormat:@"/%@",fileName];
   _url = [NSURL fileURLWithPath:imgFilePath];

}
-(id) initWithNewId
{
    self = [super initWithNewId];
    self.uploadResult = @"new file";
    self.fileDate = [self dateToString:[NSDate date]];
    return self;
    
}
-(NSDictionary *)transFormToDictionary
{
    [self validateEntityId];
    NSMutableDictionary * jDic=[[NSMutableDictionary alloc] initWithDictionary:[self dictionaryWithValuesForKeys:[self allKeys]]];
    [jDic setValue:[self.url path] forKey:@"url"];
    
    return jDic;
}
+(void)clearAttachedFile //just for test,nouse in normal run 
{
    
    NSArray *filterTypes = [NSArray arrayWithObjects:@"caf",@"png",nil];
    
    NSString *directory =  [TwERPAttachedFile localDirectory];
    
    NSString *partialPath =   [directory stringByAppendingString:@"/tw_"];      
    NSString *longestCompletion;
    NSArray *outputArray;
    
    [partialPath completePathIntoString:&longestCompletion
                                                caseSensitive:NO
                                             matchesIntoArray:&outputArray
                                                  filterTypes:filterTypes];
    
    
      
    NSFileManager *fm=[NSFileManager defaultManager];
    for (NSString *fileName in outputArray) 
            [fm removeItemAtPath:fileName error:nil];
 
}

+(void)clearOutdateFile
{

   
    NSArray *filterTypes = [NSArray arrayWithObjects:@"caf",@"png",@"jpg",@"gif",nil];
    
    NSString *directory =  [TwERPAttachedFile localDirectory];
    
    NSString *partialPath =   [directory stringByAppendingString:@"/tw_"];      
    NSString *longestCompletion;
    NSArray *outputArray;
    
    //unsigned allMatches = 
    [partialPath completePathIntoString:&longestCompletion
                                                caseSensitive:NO
                                             matchesIntoArray:&outputArray
                                                  filterTypes:filterTypes];
    
    
    unsigned long long fileSizeSum=0.0;
    unsigned long long fileSizeMax= 0.01*900000000;  //900M
    NSFileManager *fm=[NSFileManager defaultManager];
    bool toomanyfiles = NO;
    for (NSString *fileName in outputArray) {
        if(fileSizeSum>=fileSizeMax){
            toomanyfiles = YES;
            break;
        }
          else
          fileSizeSum += [[fm attributesOfItemAtPath:fileName error:nil] fileSize]; 
  }
    if (toomanyfiles)  {
        NSString *fileToClear = outputArray[0];
        [fm removeItemAtPath:fileToClear error:nil];
    }
    // allMatches = 3
    // longestCompletion = @"~/Demo/re"
    // outputArray = (@"~/Demo/readme.html", "~/Demo/readme.rtf", "~/Demo/recondite.txt")
}
-(NSString *)uploadToServer
{
    BOOL success = NO;
    success = (self.uploadResult != nil && [self.uploadResult rangeOfString:@"success"].location != NSNotFound);
    if(!success)
        self.uploadResult= [TwERPJsonAgent postFileToServer:self.url];
                        
    return self.uploadResult;
}
-(NSString *)downloadFromServer
{
     NSFileManager *fm=[NSFileManager defaultManager];

     // NSLog(@"[get file : %@", self.url);
    if([fm fileExistsAtPath:[self.url path]])
    {
        self.downloading=NO;
        return @"success";
     
    }
    [TwERPAttachedFile clearOutdateFile];
     [TwERPJsonAgent getFileFromServer:self.url];
     self.downloading=NO;
    return @"success";
}
+ (NSData *)getFileByUrl:(NSURL *) remoteUrl
{
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    NSString * fileName=[NSString stringWithFormat:@"%@",remoteUrl];
    //[remoteUrl path];
    fileName = [fileName stringByReplacingPercentEscapesUsingEncoding:encoding];
    fileName = [fileName lastPathComponent];
    
    NSString *imgFilePath =   [[self localDirectory] stringByAppendingFormat:@"/%@",fileName];            
    NSURL *localUrl = [NSURL fileURLWithPath:imgFilePath];

    NSData * fileData; 
     NSFileManager *fm=[NSFileManager defaultManager];
    if([fm fileExistsAtPath:[localUrl path]])
        fileData=[[NSData alloc] initWithContentsOfURL:localUrl];
    else {
         [self clearOutdateFile];
        
        fileData=[[NSData alloc] initWithContentsOfURL:remoteUrl];
        [fileData writeToURL:localUrl atomically:YES];
    }
     return fileData;
    
  
  // return [[NSData alloc] initWithContentsOfURL:remoteUrl];
        
}
@end
